<?php
namespace Frontend\Modules\Video\Controllers;
use Library\Constant\Constant;
use Phalcon\Paginator\Adapter\QueryBuilder;
use Phalcon\Mvc\Model\Resultset;
use Library\Pagination\Pager as Pager;
use Phalcon\Mvc\User\Component;
use Common\Models\Videos\VideoCategory;
use Common\Models\Videos\National;
use Common\Models\Videos\Artist;
use Common\Library\Common as LibraryCommon;
use Common\Models\Videos\Video;
use Common\Models\Videos\VideoCategoryLink;
use Phalcon\Mvc\View;
use Phalcon\Http\Response;
use Frontend\Modules\Video\Forms\FormCreateFilterCategory;


class CategoryController extends \FrontendController
{
    public $urlCategory = 'video/category';

    public function indexAction()
    {
        try {
            $id = abs($this->request->getQuery('id', 'int'));            
            if($id > 0){
                $this->assets
                    ->addCss('vendor/frontend/css/video/category/category.css')
                    ->addCss('vendor/frontend/css/home/home.css')
                    ->addJs('vendor/frontend/js/video/category/category_angular.js');

                $filter_country = 0;
                $filter_artist = 0;
                $filter_year = 0;
                $limit = Constant::ITEM_PER_PAGE_20;
                $currentPage = abs($this->request->getQuery('p', 'int', 1));
                if ($currentPage == 0) {
                    $currentPage = 1;
                }

                $parentCategory = VideoCategory::find(array(
                    "parent_id = $id"
                ));
                $strCategory = $id;
                foreach ($parentCategory as $category) 
                {
                    $strCategory .= ", " . $category->getId();
                }

                $sqlWhere = "1 = 1 AND video.status = 'A'";
                $conditionsWhere = array();

                $sqlWhere .= " AND FIND_IN_SET($id , category.id_path)";
                
                $url = $this->getFrontendUrl() . $this->urlCategory.'?id='.$id;
                $str_url = $url;
              
                $sort = array(
                    'national_id' => $filter_country,
                    'artist_id'   => $filter_artist,
                    'year'        => $filter_year
                );

                $builder = $this->modelsManager->createBuilder()
                    ->from(array('videoCategoryLink' => 'Common\Models\Videos\VideoCategoryLink'))
                    //->from(array('video' => ' Common\Models\Videos\Video'));
                    //->from(array('videoCategoryLink' => ' Common\Models\Videos\VideoCategoryLink'));
                    ->groupBy(array('videoCategoryLink.video_id' , 'videoCategoryLink.video_group_id'))
                    ->leftJoin('Common\Models\Videos\VideoCategory', 'category.id = videoCategoryLink.category_id','category')
                    ->leftJoin('Common\Models\Videos\Video', 'video.id = videoCategoryLink.video_id','video')
                    //->leftJoin('Common\Models\Videos\VideoDescription', 'video.id = video_description.video_id','video_description')
                    ->where($sqlWhere , $conditionsWhere)
                    ->orderBy('videoCategoryLink.position');

                $category = $this->getCategoryDetail($id);

                $filters = new FormCreateFilterCategory((object)$sort,array('edit' => true));
                $videos = new Pager(
                    new QueryBuilder(array(
                        'builder'  => $builder,
                        'limit' => $limit,
                        'page'  => $currentPage,
                    )),
                    array(
                        'layoutClass' => 'Library\Pagination\Pager\Layout\Bootstrap',
                        'rangeLength' => 5,
                        'urlMask'     => $str_url.'&page={%page_number}',
                    )
                );
                
                $sqlWhere .= ' AND image_link.type = :type: AND image_link.object_type = :object_type:';
                $conditionsWhere['type'] = 'C';
                $conditionsWhere['object_type'] = 'video';

                $videoPosters = $this->modelsManager->createBuilder()
                    ->from(array('video' => 'Common\Models\Videos\Video'))
                    ->groupBy('video.id')
                    ->leftJoin('Common\Models\Videos\VideoCategoryLink', 'video.id = category_link.video_id ','category_link')
                    ->leftJoin('Common\Models\Videos\VideoCategory', 'category.id = category_link.category_id','category')
                    ->leftJoin('Common\Models\Images\ImageLink', 'video.id = image_link.object_id','image_link')
                    //->leftJoin('Common\Models\Videos\VideoDescription', 'video.id = video_description.video_id','video_description')
                    ->where($sqlWhere , $conditionsWhere)
                    ->limit(10)
                    ->orderBy('video.id')
                    ->getQuery()
                    ->execute();

                $this->view->setVars(array(
                    'form'                  => $filters,
                    'videos'                => $videos,
                    'videoCategoryLinks'    => $videos ,
                    'category'              => $category,
                    'filter_country'        => $filter_country,
                    'filter_artist'         => $filter_artist,
                    'filter_year'           => $filter_year,
                    'num'                   => count($videos)
                ));

                $blockPoster = $this->view->getRender('poster' , 'block/video_poster' , array('videos' => $videoPosters));

                $this->view->blockPoster = $blockPoster;
                $this->view->render("video" , "category/index");
            }else{
                return $this->response->redirect('/');

            }
        } catch (\Exception $e) {
        	$this->flash->error($e->getMessage());
        }
    }

    public function categoryAction($slug)
    {   
        try {
            $keyVideoCategorySlug = $this->constant->keyCache['videoCatergory']['categorySlug'] . '-' . $slug;
            $videoCategory = $this->modelsCache->get($keyVideoCategorySlug);
            if(!$videoCategory){
                $videoCategory = VideoCategory::findFirstBySlug($slug);
            }
            
            if(!$videoCategory)
            {
                $this->flash->error("Video category was not found");
                return $this->response->redirect();

            }

            $id = $videoCategory->getId();   
            if($id > 0){
                $this->assets
                    ->addCss('vendor/frontend/css/video/category/category.css')
                    ->addCss('vendor/frontend/css/home/home.css')
                    ->addJs('vendor/frontend/js/video/category/category_angular.js');

                $filter_country = 0;
                $filter_artist = 0;
                $filter_year = 0;
                $limit = Constant::ITEM_PER_PAGE_20;
                $currentPage = abs($this->request->getQuery('p', 'int', 1));
                if ($currentPage == 0) {
                    $currentPage = 1;
                }

                $sqlWhere = "1 = 1";
                $conditionsWhere = array();
                $sqlWhere .= " AND FIND_IN_SET($id , category.id_path)";

                $url = $this->getFrontendUrl() . $videoCategory->getLinkTo();
              
                $sort = array(
                    'national_id' => $filter_country,
                    'artist_id'   => $filter_artist,
                    'year'        => $filter_year
                );

                $key = $this->constant->keyCache['video']['listVideoByCategoryId'] . '-' . $id . '-page-' . $currentPage;
                $videos = $this->modelsCache->get($key);
                if(!$videos)
                {
                    $sqlWhereCategory .= " AND (video.status = 'A' OR videoGroup.status = 'A')";
                    $builder = $this->modelsManager->createBuilder()
                        ->from(array('videoCategoryLink' => 'Common\Models\Videos\VideoCategoryLink'))
                        ->groupBy(array('videoCategoryLink.video_id' , 'videoCategoryLink.video_group_id'))
                        ->leftJoin('Common\Models\Videos\VideoCategory', 'category.id = videoCategoryLink.category_id','category')
                        ->leftJoin('Common\Models\Videos\Video', "video.id = videoCategoryLink.video_id",'video')
                        ->leftJoin('Common\Models\Videos\VideoGroup', "videoGroup.id = videoCategoryLink.video_group_id",'videoGroup')
                        ->where($sqlWhere . $sqlWhereCategory , $conditionsWhere)
                        ->orderBy('videoCategoryLink.position');

                    $videos = new Pager(
                        new QueryBuilder(array(
                            'builder'  => $builder,
                            'limit' => $limit,
                            'page'  => $currentPage,
                        )),
                        array(
                            'layoutClass' => 'Library\Pagination\Pager\Layout\Bootstrap',
                            'rangeLength' => 5,
                            'urlMask'     => '&p={%page_number}',
                        )
                    );
                    $this->modelsCache->save($key , $videos);
                }

   
                $sqlWhere .= ' AND image_link.type = :type: AND image_link.object_type = :object_type:';
                $conditionsWhere['type'] = 'C';
                $conditionsWhere['object_type'] = 'video';

                $keyVideoPosters = $this->constant->keyCache['video']['listVideoPosterByCategoryId'] . '-' . $id;
                $blockPoster = $this->modelsCache->get($keyVideoPosters);
                if(!$blockPoster){
                    $sqlWherePoster .= " AND video.status = 'A'";
                    $videoPosters = $this->modelsManager->createBuilder()
                        ->from(array('video' => 'Common\Models\Videos\Video'))
                        ->groupBy('video.id')
                        ->leftJoin('Common\Models\Videos\VideoCategoryLink', 'video.id = category_link.video_id ','category_link')
                        ->leftJoin('Common\Models\Videos\VideoCategory', 'category.id = category_link.category_id','category')
                        ->leftJoin('Common\Models\Images\ImageLink', 'video.id = image_link.object_id','image_link')
                        //->leftJoin('Common\Models\Videos\VideoDescription', 'video.id = video_description.video_id','video_description')
                        ->where($sqlWhere . $sqlWherePoster, $conditionsWhere)
                        ->limit(10)
                        ->orderBy('video.id')
                        ->getQuery()
                        ->execute();
                    $blockPoster = $this->view->getRender('poster' , 'block/video_poster' , array('videos' => $videoPosters));
                    $this->modelsCache->save($keyVideoPosters , $blockPoster);
                }
                $this->view->setVars(array(
                    'videos'                => $videos,
                    'videoCategoryLinks'    => $videos ,
                    'category'              => $videoCategory,
                    'num'                   => count($videos)
                ));

                $this->view->blockPoster = $blockPoster;
                $this->view->render("video" , "category/index");
            }else{
                return $this->response->redirect('/');

            }
        } catch (\Exception $e) {
            $this->flash->error($e->getMessage());
        }
    }

    public function getCategoryDetail($category){
        return VideoCategory::findFirstById($category);
    }
    public function  getListVideosByCategory($id,$sqlWhere,$conditionsWhere){

        return $this->modelsManager->createBuilder()
        ->from(array('video' => 'Common\Models\Videos\Video'))
        ->groupBy('video.id')
        ->join('Common\Models\Videos\VideoCategoryLink', 'video.id = category_link.video_id ','category_link')
        ->join('Common\Models\Videos\VideoCategory', 'category.id = category_link.category_id','category')
        ->join('Common\Models\Videos\VideoArtistLink', 'video.id = artist_link.video_id','artist_link')
        ->join('Common\Models\Videos\VideoDescription', 'video.id = video_description.video_id','video_description')
        ->where($sqlWhere , $conditionsWhere)
        ->orderBy('video.created_time')
        ->getQuery()
        ->execute();

    }
}

